import '@umijs/max';
import { Button, message, notification } from 'antd';
import defaultSettings from '../config/defaultSettings';
const { pwa } = defaultSettings;
const isHttps = document.location.protocol === 'https:';
const clearCache = () => {
  // remove all caches
  if (window.caches) {
    caches
      .keys()
      .then((keys) => {
        keys.forEach((key) => {
          caches.delete(key);
        });
      })
      .catch((e) => console.log(e));
  }
};

// 立即阻止 Service Worker 注册（在 UmiJS 插件注册之前）
if ('serviceWorker' in navigator) {
  // 重写 register 方法以防止注册
  const originalRegister = navigator.serviceWorker.register;
  navigator.serviceWorker.register = function(...args: any[]) {
    // 如果 pwa 为 false，阻止注册
    if (!pwa) {
      return Promise.reject(new Error('Service Worker registration is disabled'));
    }
    return originalRegister.apply(this, args);
  };
}

// if pwa is true
if (pwa) {
  // Notify user if offline now
  window.addEventListener('sw.offline', () => {
    message.warning('Currently offline');
  });

  // Pop up a prompt on the page asking the user if they want to use the latest version
  window.addEventListener('sw.updated', (event: Event) => {
    const e = event as CustomEvent;
    const reloadSW = async () => {
      // Check if there is sw whose state is waiting in ServiceWorkerRegistration
      // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
      const worker = e.detail && e.detail.waiting;
      if (!worker) {
        return true;
      }
      // Send skip-waiting event to waiting SW with MessageChannel
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = (msgEvent) => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
          } else {
            resolve(msgEvent.data);
          }
        };
        worker.postMessage(
          {
            type: 'skip-waiting',
          },
          [channel.port2],
        );
      });
      clearCache();
      window.location.reload();
      return true;
    };
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.destroy(key);
          reloadSW();
        }}
      >
        {'Refresh'}
      </Button>
    );
    notification.open({
      message: 'New content',
      description: 'Please click the "Refresh" button or manually refresh the page',
      btn,
      key,
      onClose: async () => null,
    });
  });
} else {
  // 如果 pwa 为 false，注销所有 Service Worker
  if ('serviceWorker' in navigator) {
    const unregisterAllServiceWorkers = async () => {
      try {
        // 注销所有已注册的 Service Worker
        if (navigator.serviceWorker.getRegistrations) {
          const registrations = await navigator.serviceWorker.getRegistrations();
          await Promise.all(registrations.map((registration) => registration.unregister()));
        }

        // 注销当前 Service Worker
        const registration = await navigator.serviceWorker.getRegistration();
        if (registration) {
          await registration.unregister();
        }

        // 清除缓存
        clearCache();
      } catch (error) {
        // 静默处理错误，避免在控制台显示
        // console.error('Error unregistering service workers:', error);
      }
    };

    // 立即执行注销
    unregisterAllServiceWorkers();

    // 监听 Service Worker 注册事件并立即注销
    navigator.serviceWorker.addEventListener('controllerchange', () => {
      unregisterAllServiceWorkers();
    });
  }
}
